//
//  LWXCommentController.m
//  EPA
//
//  Created by lanou3g on 16/4/25.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "LWXCommentController.h"
#import "UserinfoManager.h"
#import "LWXArticleCommentCell.h"
#import "LWXArticleCommentModel.h"
#import "LWXNetWorkRequestManager.h"
@interface LWXCommentController ()

@property (nonatomic, strong) NSMutableArray *commentArray;
@property (nonatomic, strong) UITextField *textField;
@end

@implementation LWXCommentController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
        self.commentArray = [NSMutableArray new];
    [self.tableView registerNib:[UINib nibWithNibName:@"LWXArticleCommentCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    NSDictionary *paramsData = @{@"auth":@"Wc06FCrkoq1DCMVzGMTikDJxQ8bm3Mrm2NpT9qWjwzcWP23tBKQx1c4P0",@"client":@1,@"contentid":self.model.ID,@"deviceid":@"6D4DD967-5EB2-40E2-A202-37E64F3BEA31",@"limit":@10,@"start":@0,@"version":@"3.0.6"};
    if ([UserinfoManager shareManager].auth) {
        paramsData = @{@"auth":[UserinfoManager shareManager].auth,@"client":@1,@"contentid":self.model.ID,@"deviceid":@"6D4DD967-5EB2-40E2-A202-37E64F3BEA31",@"limit":@10,@"start":@0,@"version":@"3.0.6"};
    }
    
    
    [LWXNetWorkRequestManager requestURL:[NSURL URLWithString:@"http://api2.pianke.me/comment/get"] Method:LWX_POST Params:paramsData Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            
        NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSDictionary *dataDict = jsonDict[@"data"];
        for (NSDictionary *commentDcit in dataDict[@"list"]) {
            LWXArticleCommentModel *model = [LWXArticleCommentModel new];
            [model setValuesForKeysWithDictionary:commentDcit];
            
            [self.commentArray addObject:model];
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
   
        }
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];
    view.backgroundColor = [UIColor lightGrayColor];
    self.textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, self.view.frame.size.width - 100, 40)];
    [view addSubview:self.textField];
    self.textField.borderStyle = UITextBorderStyleLine;
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 90, 10, 80, 40)];
    btn.backgroundColor = [UIColor blueColor];
    [btn setTitle:@"发送" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(sendBtnAction:) forControlEvents:(UIControlEventTouchDown)];
    [view addSubview:btn];
    [self.tableView reloadData];
    return view;
    
}

- (void)sendBtnAction:(UIButton *)btn {
    if ([UserinfoManager shareManager].auth) {
        
    
    NSURL *url = [NSURL URLWithString:@"http://api2.pianke.me/comment/add"];
    [LWXNetWorkRequestManager requestURL:url Method:LWX_POST Params:@{@"auth":[UserinfoManager shareManager].auth,@"client":@1,@"content":self.textField.text,@"contentid":self.model.ID,@"deviceid":@"6D4DD967-5EB2-40E2-A202-37E64F3BEA31",@"version":@"3.0.6"} Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSMutableDictionary *jsonDict=  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSString *result = jsonDict[@"result"];
            NSLog(@"%@",result);
            NSString *str = jsonDict[@"data"][@"msg"];
            NSLog(@"%@",str);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
           self.textField.text = nil;
             [self.tableView reloadData];
        });

    }];

    }else {
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请登录账号" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
        [alertC addAction:alertAction];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:alertC animated:YES completion:nil];
        });
        
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.commentArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LWXArticleCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.model = self.commentArray[indexPath.row];

    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    LWXArticleCommentModel *model = self.commentArray[indexPath.row];
    NSString *content = model.content;
    NSDictionary *dict = @{NSFontAttributeName : [UIFont systemFontOfSize:16]};
    CGRect rect = [content boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 20, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dict context:nil];

    return rect.size.height + 90;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
